package com.wang.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wang.Dto.UserDTO;
import com.wang.Dto.UserPasswordDTO;
import com.wang.common.Constants;
import com.wang.common.Result;
import com.wang.entity.User;
import com.wang.exception.ServiceException;
import com.wang.mapper.UserMapper;
import com.wang.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.utiles.TokenUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author anonymous
 * @since 2022-05-16
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private static final Log log=Log.get();



    @Resource
    private UserMapper userMapper;

    @Resource
    @Lazy
    private UserService userService;
    @Override
    public UserDTO login(UserDTO userDTO) {
        User one=getUserInfo(userDTO);
        if( one != null){
            BeanUtil.copyProperties(one,userDTO,true);
            String token = TokenUtils.genToken(one.getId().toString(), one.getPassword());
            userDTO.setToken(token);
            return userDTO;
        }else{
            throw new  ServiceException(Constants.CODE_600,"用户名或密码错误");
        }
    }

    @Override
    public User register(UserDTO userDTO) {
        User one=getUserInfo(userDTO);
        if( one == null){
            one = new User();
            BeanUtil.copyProperties(userDTO,one,true);

           save(one);
        }else{
            throw new  ServiceException(Constants.CODE_600,"用户已存在");
        }
        return one;
    }
    @Override
    public void updatePassword(UserPasswordDTO userPasswordDTO) {
        int update = userMapper.updatePassword(userPasswordDTO);
        if (update < 1) {
            throw new ServiceException(Constants.CODE_600, "密码错误");
        }
    }
//    @Override
//    public Page<User> findPage(Page<User> page, String username, String nickname) {
//        return userMapper.findPage(page, username, nickname);
//    }
    private User getUserInfo(UserDTO userDTO){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",userDTO.getUsername());
        queryWrapper.eq("password",userDTO.getPassword());
        User one;
        try {
            one=getOne(queryWrapper);
        }catch (Exception e){
            log.error(e);
            throw new ServiceException(Constants.CODE_500 ,"系统错误");
        }
        return one;
    }
}
